package com.itheima.web.filter; /**
 * @author Xiao
 * @date 2021/9/4
 */

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

//@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        //ServletRequest强转为HttpServletRequest，才能调用getSession()方法
        HttpServletRequest req = (HttpServletRequest) request;
        //放行与登陆注册相关的资源路径(图片，css，js，登陆注册页面，登陆注册请求)
        String[] urls = {"/index.jsp", "/login.jsp", "/register.jsp", "/css/",
                "/imgs/", "/loginServlet", "/registerServlet", "/checkCodeServlet", "/selectUserServlet"};
        String url = req.getRequestURL().toString();
        for (String s : urls) {
            //如果访问路径包含上述资源路径，放行     contains()
            if (url.contains(s)) {
                chain.doFilter(request,response);
                return;
            }
        }
        //通过获取HttpSession对象，判断是否已存在user对象
        HttpSession session = req.getSession();
        Object user = session.getAttribute("user");
        //判断用户是否登陆
        if (user != null) {
            //登陆了就放行
            chain.doFilter(request, response);
        } else {
            //没登录给出提示
            req.setAttribute("login_msg", "您尚未登陆!");
            req.getRequestDispatcher("login.jsp").forward(req, response);
        }
    }

    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }
}
